﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Windows.Forms;
using System.Threading;

namespace ClipboardTranslator
{
    static class Program
    {
        static EventWaitHandle presence_event = null;

        public static readonly string MailTo = "undwad@mail.ru; britpopcommie@gmail.com";

        public static readonly string ApplicationPath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;

        public static readonly string ApplicationFolder = Path.GetDirectoryName(ApplicationPath);

        public static readonly string UserDataFolder = Application.LocalUserAppDataPath;

        public static readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version;

        public static readonly string ApplicationVersion = Version.Major.ToString() + '.' + Version.Minor + '.' + Version.MinorRevision;

        static Program()
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (null != e.ExceptionObject && e.ExceptionObject is Exception)
                ProcessException(e.ExceptionObject as Exception);
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            ProcessException(e.Exception);
        }

        public static void ProcessException(Exception e)
        {
            DialogResult result = MessageBox.Show(null, e.ToString(), Localization.Localize("Send error text to developer") + '?', MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error);
            if (DialogResult.Yes == result)
                Process.Start("mailto:" + MailTo + "?subject=Clipboard Translator " + Version + " Exception&body=" + e.ToString());
            if (DialogResult.Cancel != result)
                Environment.Exit(-1);
        }

        [STAThread]
        static void Main()
        {
            bool single = false;
            presence_event = new EventWaitHandle(false, EventResetMode.AutoReset, "Clipboard Translater Application Presence Event", out single);

            if (single)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());
            }
        }
    }
}
